<template>
  <div class="fill-word">
    <div class="answer-list">
      <div class="answer-item" v-for="(answer,aIndex) in answerList" :key="aIndex" @click="remove(answer,aIndex)">{{answer.value}}</div>
    </div>
    <div class="select-list">
      <button plain="true" class="select-item" :class="{select:item.select}" v-for="item in selectList" :key="item.id" @getuserinfo="getUserInfo($event)" @click="select(item)" open-type="getUserInfo" lang="zh_CN">{{item.value}} </button>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  props: ["isTip", "subject"], //isTip 提示开关
  data() {
    return {
      answerList: [], //答案列表
      selectList: [],
      touchContext: null,
      user:null,
    };
  },

  watch: {
    subject() {
      this.initAnsewr();
      this.initSelect();
    },
    isTip() {
      this.makeTip(); //处理提示
    }
  },
  computed: {
    ...mapState(["energy", "tipEnergy", "userInfo", "isAuthorize"])
  },
  methods: {
    ...mapMutations(["setUserInfo"]),

    getWatchAnswerList() {
      this.$watch(
        "answerList",
        function(val, oldVal) {
          this.checkAnswer(val); //检查答案
        },
        {
          deep: true
        }
      );
    },
    initAudio() {
      this.touchContext = wx.createInnerAudioContext();
      this.touchContext.src = "static/audio/btn.mp3";
      this.touchContext.volume = 0.9;
    },
    playAudio() {
      this.touchContext.play();
    },
    stopAudio() {
      this.touchContext.stop();
    },
    initAnsewr() {
      //初始化答案列表
      this.answerList = [];
      for (let i = 0; i < this.subject.answer.length; i++) {
        let obj = {
          fromId: 0,
          value: ""
        };
        this.answerList.push(obj);
      }
    },

    strUnique(str) {
      //字符串去重
      let se = new Set();
      str = str.split("");
      for (let i = 0; i < str.length; i++) {
        se.add(str[i]);
      }
      str = Array.from(se).join("");
      return str;
    },
    randomSort(a) {
      //数组随机
      var arr = a,
        random = [],
        len = arr.length;
      for (var i = 0; i < len; i++) {
        var index = Math.floor(Math.random() * (len - i));
        random.push(a[index]);
        arr.splice(index, 1);
      }
      return random;
    },
    initSelect() {
      //初始化选择列表
      let str = "",
        len = 0,
        list = [],
        successIndex, //正确选项下标
        random;
      this.selectList = [];
      this.subject.optionList.forEach((item, index) => {
        // str += item.name;
        // len = str.length;
        if (item.sortId == this.subject.optionSortId) {
          successIndex = index;
        }
      });

      //超过21个字
      // if (len > 21) {
      str = "";
      this.subject.optionList.forEach((item, index) => {
        if (successIndex != index) {
          str += item.name;
          len = str.length;
        }
      });
      console.log(str);
      // }
      // if (len < 21) {
      let newStr = "";
      str = this.strUnique(str, len);
      console.log(str);
      str += this.subject.optionList[successIndex].name;
      console.log(str);

      str = str.replace(/(^\s*)|(\s*$)/g, "");
      len = str.length;
      if (len > 21) {
        str = str.substring(len - 21);
      }
      if (len < 21) {
        newStr = this.subject.randomStr.substring(0, 21 - len);
      }
      str += newStr;
      len = str.length;
      // }
      list = str.split("");
      //---star重新排列字符串
      // list.sort();
      list = this.randomSort(list);
      // ---end 排列
      list.forEach((item, index) => {
        let obj = {
          id: index,
          value: item,
          select: false
        };
        this.selectList.push(obj);
      });
    },

    getNullIndex() {
      for (let i = 0; i < this.answerList.length; i++) {
        if (this.answerList[i].value == "") {
          return i;
        }
      }
    },
    getUserInfo(event) {
      let data = event.mp.detail.userInfo;
      if (this.isAuthorize == 0 && data) {
        // data = event.mp.detail.userInfo;
        this.setUserInfo(data);
        wx.setStorage({
          key: "isAuthorize",
          data: "1"
        });
        this.store.commit("setAuthorize", 1);
        // TODO 调用授权接口处理业务
        console.log("调用授权接口一次");
      } else if (this.isAuthorize == 1 && !this.userInfo) {
        this.setUserInfo(data);
      }
    },
    select(item) {
      //选择选项
      if (!item.select && this.isAuthorize == 1) {
        this.playAudio();
        setTimeout(() => {
          this.stopAudio();
        }, 120);
        let index = this.getNullIndex();
        if (index != undefined) {
          item.select = true;
          this.$set(this.answerList[index], "fromId", item.id);
          this.$set(this.answerList[index], "value", item.value);
          this.answerList = this.answerList;
        }
      }
    },

    remove(item, aIndex) {
      if (item.value != "") {
        this.playAudio();
        setTimeout(() => {
          this.stopAudio();
        }, 100);
      }

      //清除选项
      this.answerList[aIndex].value = "";
      // 排除提示增加的答案
      this.selectList[item.fromId].select = false;
    },

    makeTip() {
      let answer = this.subject.answer.split("");
      // 清除错误所有答案
      for (let i = 0; i < this.answerList.length; i++) {
        if (this.answerList[i].value != answer[i]) {
          this.remove(this.answerList[i], i);
        }
      }
      // 补充一个正确答案
      let index = this.getNullIndex();
      if (index != undefined) {
        let answerWord = answer[index];
        for (let i = 0; i < this.selectList.length; i++) {
          if (
            this.selectList[i].value == answerWord &&
            !this.selectList[i].select
          ) {
            this.selectList[i].select = true;
            this.answerList[index].value = answerWord;
            this.answerList[index].fromId = this.selectList[i].id;
            break;
          }
        }
        // this.answerList[index].value = answer[index];
        // this.answerList[index].fromId = -1; //提示 设置为-1 区分正常点击
      }
    },
    checkAnswer(val) {
      let fullAnswer = true,
        finalAnswer = "";
      val.forEach(item => {
        if (item.value == "") {
          fullAnswer = false;
        } else {
          finalAnswer += item.value;
        }
      });

      // 填满答案在判断是否正确
      if (fullAnswer) {
        if (finalAnswer == this.subject.answer) {
          this.$emit("getSuccess", finalAnswer);
        } else {
          wx.showToast({
            title: "回答错误",
            icon: "none",
            duration: 500
          });
          this.$emit("getFail");
        }
      }
    }
  },
  mounted() {
    // 初始化 答案长度
    this.initAnsewr();

    this.initSelect();

    this.initAudio();
    this.getWatchAnswerList(); //创建深度监听 答案列表
  }
};
</script>

<style lang="scss" scoped>
.fill-word {
  text-align: center;
}
.answer-list {
  width: 100%;
  text-align: center;
  // padding:26rpx 0;
}
.answer-item {
  display: inline-block;
  width: 72rpx;
  height: 72rpx;
  line-height: 72rpx;
  text-align: center;
  border-radius: 8rpx;
  background: #ffe2c9;
  font-size: 40rpx;
  color: #b14e53;
  margin-right: 16rpx;
  vertical-align: top;
  font-weight: bold;
  &:last-child {
    margin-right: 0;
  }
}
.select-list {
  width: 690rpx;
  margin: 26rpx auto 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
.select-item {
  width: 96rpx;
  height: 96rpx;
  text-align: center;
  line-height: 80rpx;
  color: #fff;
  font-weight: bold;
  font-size: 42rpx;
  border: none;
  background-size: 96rpx 96rpx;
  background-image: url("");
}
.select {
  opacity: 0;
}
</style>
